//
//  HRRefreshControl.swift
//  weiBo
//
//  Created by helong on 16/7/16.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
//  自定义下拉刷新的高度
private let RefreshControlHeight: CGFloat = 50
//  定义状态枚举
enum RefreshStatus: Int {
    case Normal//   下拉刷新状态
    case Pulling//  松手刷新状态
    case Refreshing//   正在刷新
    
}
class HRRefreshControl: UIControl {
    //  当前滚动视图
   private var currentScrollView: UIScrollView?
    //  设置默认当前刷新状态
    var refreshStatus: RefreshStatus = .Normal {
        //  当状态切换的时候
        didSet{
            switch refreshStatus{
            case .Normal:
                print("下拉刷新")
                //  下拉刷新
                messageLabel.text = "下拉刷新"
                //  关闭菊花转,显示箭头
                indicatorImage.hidden = false
                activityIndicator.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.indicatorImage.transform = CGAffineTransformIdentity
                })
                //  判断是否应是正在刷新的状态,如果是就执行动画
                if oldValue == .Refreshing {
                //  取消悬停效果
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.currentScrollView?.contentInset.top -= RefreshControlHeight
                })
                }
            case .Pulling:
                print("松手刷新")
                //  松手刷新
                messageLabel.text = "松手刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.indicatorImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
               
            case .Refreshing:
                //  正在刷新
                messageLabel.text = "正在刷新"
                print("正在刷新")
                //  开启菊花转,隐藏箭头
                activityIndicator.startAnimating()
                indicatorImage.hidden = true
                
                //  添加悬停效果
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.currentScrollView?.contentInset.top += RefreshControlHeight
                })
                
                //  开始请求数据,在外面监听
                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }
    //  懒加载文本框
    private lazy var messageLabel: UILabel = {
        let lbl = UILabel(textColor: UIColor.grayColor(), fontSize: 14)
        lbl.text = "下拉刷新"
        return lbl
    }()
    //  懒加载箭头图片框
    private lazy var indicatorImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //  懒加载菊花转
    private lazy var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //  设置背景颜色
        self.backgroundColor = randomColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     // MARK: - 添加控件,设置约束(全部用系统的约束,增加通用性)
    private func setupUI(){
        addSubview(messageLabel)
        addSubview(indicatorImage)
        addSubview(activityIndicator)
        
        indicatorImage.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        
        //  指示图片约束
        addConstraint(NSLayoutConstraint(item: indicatorImage, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -25))
        addConstraint(NSLayoutConstraint(item: indicatorImage, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
//        indicatorImage.snp_makeConstraints { (make) -> Void in
//            make.centerX.equalTo(self).offset(-25)
//            make.centerY.equalTo(self)
//        }
        //  messageLabel的约束
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 25))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
//        messageLabel.snp_makeConstraints { (make) -> Void in
//            make.centerX.equalTo(self).offset(25)
//            make.centerY.equalTo(self)
//        }
        //  菊花转约束
        addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .CenterX, relatedBy: .Equal, toItem: indicatorImage, attribute: .CenterX, multiplier: 1, constant: 0))
         addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: indicatorImage, attribute: .CenterY, multiplier: 1, constant: 0))
//        activityIndicator.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(indicatorImage)
//        }
        
    }
     // MARK: - 将要添加到父控件的时候调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        //  设置刷新控件的大小
        self.frame.size = CGSizeMake(scrollView.frame.size.width, RefreshControlHeight)
        //  设置高度
        self.frame.origin.y = -RefreshControlHeight
        //  添加监听者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        //  设置
        
        currentScrollView = scrollView
    }
 // MARK: - 使用kvo监听滚动
    /**
    使用kvo监听滚动
    - parameter keyPath: 监听的类容
    - parameter object:  监听的对象
    - parameter change:  监听的变化
    - parameter context: nil
    */
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(currentScrollView?.contentOffset.y)
//        print(change)
        guard let scrollView = currentScrollView else{
            return
        }
        //  如果是下拉的状态: 下拉有两种状态: 下拉刷新,松手刷新
        if scrollView.dragging {
            //  下拉执行此句
            if scrollView.contentOffset.y <= -(RefreshControlHeight + scrollView.contentInset.top) && refreshStatus == .Normal {
                
//                print("松手刷新")
                refreshStatus = .Pulling
                
                
            }else if scrollView.contentOffset.y > -(RefreshControlHeight + scrollView.contentInset.top) && refreshStatus == .Pulling{
                
//                print("下拉刷新")
                refreshStatus = .Normal
                
            }
        }else {//    如果不是下拉,就是正在刷新
            if refreshStatus == .Pulling  {
//            print("正在刷新")
                //  将状态变为正在刷新,记得刷新完之后状态给为下拉刷新
            refreshStatus = .Refreshing
                
            }
            
        }
        
        
    }
     // MARK: - 结束刷新
    func endRefreshing(){
        self.refreshStatus = .Normal
    }
    
     // MARK: - 移除监听
    deinit{
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
